package com.suray.system.run.ding;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.wcs.service.init.SystemInit;
import com.suray.wcs.service.system.entity.WareHouseDB;
import com.suray.wcs.service.system.service.impl.WareHouseDBServiceImpl;
import com.taobao.api.ApiException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;


@Component
public class DingRobot {

    private static final String DING_URL = "https://oapi.dingtalk.com/robot/send?access_token=";

    /**
     * 向钉钉推送信息
     *
     * @param content
     */
    public static void pauseMessage(String content) {
        //组装请求内容
        Long timestamp = System.currentTimeMillis();
        String sign = getSign(timestamp);
        String url = DING_URL + SystemInit.wareHouseDB.getAccessToken() + "&timestamp=" + timestamp + "&sign=" + sign;
        DingTalkClient client = new DefaultDingTalkClient(url);
        OapiRobotSendRequest request = new OapiRobotSendRequest();

        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        request.setText(text);
        try {
            client.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    private static String getSign(Long timestamp) {
        try {
            String stringToSign = timestamp + "\n" + SystemInit.wareHouseDB.getSecret();
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SystemInit.wareHouseDB.getSecret().getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            return sign;
        } catch (Exception e) {
            return null;
        }
    }

}
